isChatScroll = false;


prepareChannelChat = function(sToken){
	var channel = new goog.appengine.Channel(sToken);
    var socket = channel.open();
    socket.onopen = onOpened;
    socket.onmessage = onMessage;
    socket.onerror = onError;
    socket.onclose = onClose;
    
    //prepare for chat log
    jQuery('#msg_box').keyup(function (e){
		if(e.keyCode == 13)
		{
			sendMessageChat();
		}
	});
	jQuery('#chat_story').scroll(function(){
		isChatScroll = true;
	});
	
};

createToken = function(){
	jQuery.ajax ({
		type : 'POST',
		url : '/channel_chat',
		dataType: 'json',
		data : {action:'create_token'},
		success : function(data) {
			if(data.token)
			{
				prepareChannelChat(data.token);
			}
		},
		error: function(jqXHR, textStatus, errorThrown){
			alert('Network error');
			window.location.reload();
		}
	});
};

getToken = function(){
	jQuery.ajax ({
		type : 'POST',
		url : '/channel_chat',
		dataType: 'json',
		data : {action:'get_token'},
		success : function(data) {
			if(data.token)
			{
				prepareChannelChat(data.token);
			}
		},
		error: function(jqXHR, textStatus, errorThrown){
			alert('Network error');
			window.location.reload();
		}
	});
};

sendMessageChat = function(){
	isChatScroll = false;
	var sMessage = jQuery('#msg_box').val();
	jQuery('#msg_box').val('');
	sendMessage('send_message', sMessage);
}

sendMessage = function(sAction, sMessage) {
	var path = '/channel_chat';
	if (sMessage) {
		path += '?action=' + sAction + '&message=' + sMessage;
		var xhr = new XMLHttpRequest();
		xhr.open('POST', path, true);
		xhr.send();
	}
};

onOpened = function() {
	sendMessage('join', 'joined');
	getOldMessages();
};

checklength = function(i){  
    if (i<10){  
     i="0"+i;}  
     return i;  
};

refreshUserOnline = function(aAllUser){
	$('#user_online').html('');
	for(i in aAllUser)
	{
		var eUserEle = $(
'<div class="online_user">' +
	'<span class="online_user_name">' +
		aAllUser[i] +
	'</span>' +
'</div>');
		$('#user_online').append(eUserEle);
	}
};

onMessage = function(e){
	eval("var data = " + e.data);
	if(data.code == 1)
	{
		data = data.data;
		var isEmpty = jQuery('#chat_story').html();
		var time = new Date(data._lTime);
		
		var sTime = '[' + checklength(time.getHours()) + ':' + checklength(time.getMinutes()) + ':' + checklength(time.getSeconds()) +']';
		var sUsername = data._sUserName;
		var sMessage = data._sMessage;
		var eChatEle = $(
'<div class="log_chat">' +
	'<span class="log_chat_time">' +
		sTime +
	'</span>' +
	'<span class="log_chat_user">' +
		sUsername + 
	'</span>' +
	'<div class="log_chat_message">' +
		'<span>' +
			sMessage +
		'</span>' + 
	'</div>' +
'</div>');

		$('#chat_story').append(eChatEle);

		if(isChatScroll == false)
		{
			jQuery('#chat_story').animate({ scrollTop: jQuery('#chat_story').prop("scrollHeight") }, "slow", function(){
				isChatScroll = false;	
			});
		}
	}
	else if(data.code == 2)
	{
		//console.log(data);
		data = data.data;
		refreshUserOnline(data.all_user);
	}
	else if(data.code == 3)
	{
		if(sEmail != data.email)
		{
			data = data.data;
			black_board.drawToBlackBoard(jQuery.parseJSON(data.all_pos));
		}
	}
};

onError = function(e){
	//console.log(e);
	if(e.code == 500)
		createToken();
	else
		console.log("onError");
};
onClose = function(){
	console.log("onClose");
};

clearMessageChat = function(){
	jQuery('#chat_story').html('');
};

iTimeOldMessages = 0;

getOldMessages = function(){
	jQuery.ajax ({
		type : 'POST',
		url : '/channel_chat',
		dataType: 'json',
		data : {action:'get_old_message', old_time: iTimeOldMessages},
		success : function(data) {
			if(data.old_time)
			{
				iTimeOldMessages = data.old_time;
			}
			if(data.old_message && data.old_message.length !== 0)
			{
				
				for(i in data.old_message)
				{
					var time = new Date(data.old_message[i]._lTime);
					
					var sTime = '[' + checklength(time.getHours()) + ':' + checklength(time.getMinutes()) + ':' + checklength(time.getSeconds()) +']';
					var sUsername = data.old_message[i]._sUserName;
					var sMessage = data.old_message[i]._sMessage;
					var eChatEle = $(
'<div class="log_chat">' +
	'<span class="log_chat_time">' +
		sTime +
	'</span>' +
	'<span class="log_chat_user">' +
		sUsername + 
	'</span>' +
	'<div class="log_chat_message">' +
		'<span>' +
			sMessage +
		'</span>' + 
	'</div>' +
'</div>');
					$('#view_old_link').after(eChatEle);
				}
			}
		},
		error: function(jqXHR, textStatus, errorThrown){
			alert('Network error');
			window.location.reload();
		}
	});
};

jQuery(document).ready(function() {
	if(undefined != sEmail)
	{
		getToken();
	}
});

